import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/http/bean/http_data.dart';
import 'package:app/src/http/bean/user.dart';
import 'package:app/src/http/model/submit_model.dart';
import 'package:app/src/manager/audit_manager.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/ui/route/works/public/image/ui_image_upload.dart';
import 'package:app/src/utils/image_path_utils.dart';

import '../../../../../http/bean/worksdo/equipment_management_bean.dart';
import '../../../../../http/model/equipment_management_model.dart';
import '../../../../../http/model/material_requisition_model.dart';
import '../../../works/public/review_submitted.dart';

///审核提交
class ReviewSubmittedStateful2 extends StatefulWidget {
  //数据
  EquipmentResponseData? mData = null;

  //提交之前回调,用于提交参数SubData赋值。
  ResponseCallbackWithT<EquipmentResponseData>? _callbackWithT = null;

  //提交前；用于验证数据。
  ResponseCallbackWithBoolResultII? _callbackWithBoolResultII = null;

  ReviewSubmittedStateful2(this.mData,
      {ResponseCallbackWithT<EquipmentResponseData>? callbackWithT = null,
      ResponseCallbackWithBoolResultII? callbackWithBoolResult = null}) {
    this._callbackWithT = callbackWithT;
    this._callbackWithBoolResultII = callbackWithBoolResult;
  }

  @override
  _State createState() => _State();
}

class _State extends State<ReviewSubmittedStateful2> {
  _Presenter presenter = _Presenter();

  @override
  void initState() {
    super.initState();
    presenter?.mData = widget?.mData;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    AuditManager.getAuditManager()
        .setDetailsWithAuto(false, "review_submitted.dart"); //fixme 不在审核详情页面。
  }

  @override
  Widget build(BuildContext context) {
    // AuditManager.setDetailsWithAuto(
    //     true, "review_submitted.dart"); //fixme 当前在审核详情页面。现在需求任然需要显示通知信息。。
    return _body(context);
  }

  Widget _body(BuildContext context) {
    return StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
      presenter.setStateBody = setState;
      List<Widget> children = [];
      var topMargin = 16.0;

      children.add(_EstimatedWorkingHours(context)); //预估工时
      var submitName = AppStrings.of(context).Firmassignment; //确定派工
      var SubmitAudit = MaterialButton(
        onPressed: () {
          _focusNode?.unfocus(); //fixme 清除文本框的焦点,防止弹框消时的时候，输入法软键盘自动弹出。
          var b = true;
          if (widget._callbackWithBoolResultII != null) {
            var b2 =
                widget._callbackWithBoolResultII?.call(); //fixme 提交之前验证数据格式。
            if (b2 != null) {
              b = b2;
            }
          }
          if (b) {
            presenter?.contractapply(context, widget._callbackWithT);
          }
        },
        color: ColorUtils.parseColor("#5985F0"),
        textColor: Colors.white,
        padding: EdgeInsets.all(15),
        elevation: 0,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(8), bottomLeft: Radius.circular(8))),
        child: Text(submitName),
      );
      //返回列表
      var ReturnsList = MaterialButton(
        onPressed: () {
          AppRouteHelper.pop(context);
        },
        color: ColorUtils.parseColor("#8F97AC"),
        textColor: Colors.white,
        padding: EdgeInsets.all(15),
        elevation: 0,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topRight: Radius.circular(8), bottomRight: Radius.circular(8))),
        child: Text(AppStrings.of(context).ReturnsList),
      );
      var row = Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [Expanded(child: SubmitAudit), Expanded(child: ReturnsList)],
      );
      children.add(row);

      return Container(
        padding: EdgeInsets.only(left: 8, right: 8, top: topMargin, bottom: 16),
        child: Column(
          children: children,
        ),
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(
                color: Colors.black, blurRadius: 10, offset: Offset(0, 10))
          ],
        ),
      );
    });
  }

  ///预估工时
  StateSetter? _setState;
  FocusNode? _focusNode = FocusNode();

  Widget _EstimatedWorkingHours(BuildContext context) {
    var textStyle = TextStyle(color: Colors.black, fontSize: 16);
    return StatefulBuilder(
      builder: (context, setState) {
        _setState = setState;
        var text = Text(
          AppStrings.of(context).Estimatedworkinghours + ":",
          style: textStyle,
        ); //预估工时
        var textFormField = TextFormField(
            focusNode: _focusNode,
            cursorColor: Colors.blueAccent,
            //鼠标颜色
            // controller: _decimalFormatterController!,
            //文本控制器
            onChanged: (value) {
              //文本发生变化
              setState(() {
                try {
                  presenter?.mData?.Hours = value?.trim(); //fixme 预估工时赋值
                } catch (e) {}
              });
            },
            style: textStyle,
            inputFormatters: [
              LengthLimitingTextInputFormatter(7), //fixme 这里预计工时，限制7位数，限制两位小数。
              DecimalFormatter(
                  isEmpty: true, isNegative: false, decimalPoint: 2)
            ],
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
                // hintText: AppStrings.of(context).Clicktoenterhours,//点击输入工时;感觉不显示比较好。
                suffix: Text(AppStrings.of(context).hours),
                focusedBorder: UnderlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(0)),
                    borderSide: BorderSide(color: Colors.blueAccent, width: 1)),
                enabledBorder: UnderlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(0)),
                    borderSide: BorderSide(color: Colors.grey, width: 1))));
        return Row(
          children: [
            text,
            Container(
              child: Container(
                child: textFormField,
                margin: EdgeInsets.only(left: 8),
                width: 100,
                height: 40,
                alignment: Alignment.centerLeft,
              ),
              alignment: Alignment.centerLeft,
              height: 50,
            )
          ],
        );
      },
    );
  }
}

class _Presenter {
  ///body视图状态
  StateSetter? setStateBody;

  TextEditingController? textEditingController = null;

  EquipmentResponseData? mData = null;

  ///提交审核
  contractapply(BuildContext context,
      ResponseCallbackWithT<EquipmentResponseData>? _callbackWithT) {
    AuditManager.getAuditManager().setDetailsWithAuto(true,
        "review_submitted2.dart"); //fixme 在审核详情页面,正在提交的时候，不要显示通知信息。没有提交的时候，还是要显示的。
    _callbackWithT?.call(mData!); //fixme 提交之前回调，用于提交参数赋值。
    //fixme 先上传图片
    UiImageUpLoad.syspicupload(context, (value) {
      // _subData?.pics = value; //fixme 图片地址
      //fixme 审核提交
      EquipmentManagementModel.DispatchingRepairOrder(context, mData, true)
          ?.then((value) {
        isRefreshPreviousAppList = true; //fixme true返回上一个页面，列表会刷新。
        if (value.isSuccessForCode()) {
          Toast.showSuccess(
              AppStrings.of(context).SubmitSuccessfully, context); //提交成功
          UiImageUpLoad.clear(); //提交成功，清除本地图片
          AppRouteHelper.pop(context, true); //关闭当前审核页面
          AuditManager.getAuditManager().setDetailsWithAuto(
              false, "review_submitted2.dart"); //fixme 审核详情页面提交结束，可以显示通知信息。
        } else {
          //提示错误信息
          AppDialog.showDialogWithInfo(context, content: value.MsgDetail);
          AuditManager.getAuditManager().setDetailsWithAuto(
              false, "review_submitted2.dart"); //fixme 审核详情页面提交结束，可以显示通知信息。
        }
      });
    });
  }
}
